#include "dialog.h"
#include "ui_dialog.h"

const quint16 port = 6666;
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{

    ui->setupUi(this);
    server = new QTcpServer(this);
    connect(ui->pushButton,SIGNAL(clicked(bool)),
            this,SLOT(startServer()));
    connect(ui->pushButton_2,SIGNAL(clicked(bool)),
            this,SLOT(sendData()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::startServer()
{
    server->listen(QHostAddress::Any,port);
    connect(server,SIGNAL(newConnection()),
            this,SLOT(connectServer()));
}


void Dialog::connectServer()
{
    //获取客户端
    socket = server->nextPendingConnection();
    connect(socket,SIGNAL(readyRead()),
            this,SLOT(recvData()));
}

void Dialog::sendData()
{
    socket->write(ui->textEdit_2->toPlainText().toLatin1());
    socket->flush();
}
 void Dialog::recvData()
 {
     QByteArray str;
     str = socket->readAll();
     if(!str.isEmpty())
     {
         ui->textEdit->append(QString::fromLocal8Bit(str) );
     }
 }
